package siau.android.base

import android.app.ActivityManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.text.TextUtils
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ProcessLifecycleOwner
import com.alibaba.android.arouter.launcher.ARouter
import com.igexin.sdk.PushManager
import com.qiniu.android.common.FixedZone
import com.qiniu.android.storage.Configuration
import com.qiniu.android.storage.UploadManager
import com.squareup.leakcanary.LeakCanary
import com.tencent.mm.opensdk.constants.ConstantsAPI
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import com.umeng.analytics.MobclickAgent
import com.umeng.commonsdk.UMConfigure
import hhm.android.base.application.BaseApplication
import hhm.android.library.utils.DataStoreUtils
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.async
import siau.android.http.model.CidRequest
import siau.android.http.model.GetDefaultFamilyResponse
import siau.android.library.KeyString
import java.util.*

class SBApplication : BaseApplication(), CoroutineScope by MainScope() {

    companion object {

        const val qaString = "https://www.sevenbubble.com/bubble-page/pages/FQA/index"
        const val privacyString = "https://www.sevenbubble.com/agreement/privacy_agreement.html"
        const val usaString = "https://www.sevenbubble.com/agreement/user_service_agreement.html"

        lateinit var userData: GetDefaultFamilyResponse
        var blueToothUtil: BlueToothUtil? = null
        lateinit var api: IWXAPI
        lateinit var uploadManager: UploadManager

        var hasWeightMachine: Boolean = false
        var hasHeightMachine: Boolean = false
        var hasToothBrushMachine: Boolean = false
        var latitude: String = ""//获取纬度
        var longitude: String = ""//获取经度
        var netWorkState: Boolean? = false//网络状态
        var version: String = ""
        lateinit var instance: SBApplication
//        var startCalculate = MutableLiveData(false)
//        var calculateType: Int = 1//1体重 2身高
//        var calculateChild: Int = 0//childId
        val appForeground = MutableLiveData(true)
        var refreshMainActivityUI: Boolean = false
        var noFamilyActivityShow = false
        var becomeCreator: Boolean = false
        var mainHomePageSelect = 0
        var communityChildId = 0
        var startShowChangeFamilySheet = false
        var mainPageChange = MutableLiveData<MainPageChangeData>(null)
        lateinit var cid: String

        fun checkHasChildren(): Boolean {
            return if (userData.children != null) {
                userData.children!!.size > 0
            } else {
                userData.children = ArrayList()
                false
            }
        }

        fun getBlueToothUtils(): BlueToothUtil {
            return if (blueToothUtil == null) {
                blueToothUtil = BlueToothUtil.getInstance()
                blueToothUtil!!
            } else {
                blueToothUtil!!
            }
        }

        fun sendOnePointReceiver(showToast: Boolean?) {
            instance.onePointHappen(showToast)
        }

        fun clearBlueToothData() {
            blueToothUtil?.stopScan()
            blueToothUtil?.disConnect()
            userData.deviceList?.clear()
            blueToothUtil?.scanDevices?.clear()
            blueToothUtil?.scanDevicesNum?.value = 0
        }
    }

    private val APP_ID = "wx34648f13dc13e481"

    //将Bugly，x5内核初始化，SP的读写，友盟等组件放到子线程中初始化。

    override fun onCreate() {
        super.onCreate()

        PushManager.getInstance().initialize(this)

        if (getName() == packageName) {

            instance = this
            //---------------------------------需要马上初始化

            ARouter.openDebug()
            ARouter.init(this)

            //初始化存储工具，获取token等信息
            DataStoreUtils.init(this)

            //计时开始
            ProcessLifecycleOwner.get().lifecycle.addObserver(SBaseApplicationLifeCycle())


            //---------------------------------可以稍后初始化
            regToWx()

            //友盟统计
            UMConfigure.init(this, "5fec377eadb42d582695cfb6", "OnLine", UMConfigure.DEVICE_TYPE_PHONE, "")
//            UMConfigure.init(this, "5fec377eadb42d582695cfb6", "sevenbubble", UMConfigure.DEVICE_TYPE_PHONE, "")
            MobclickAgent.setPageCollectionMode(MobclickAgent.PageMode.AUTO)
            MobclickAgent.setCatchUncaughtExceptions(true)

            setNetworkAlertTip()

            //七牛
            val config: Configuration = Configuration.Builder().connectTimeout(90) // 链接超时。默认90秒
                .useHttps(true) // 是否使用https上传域名
                .useConcurrentResumeUpload(true) // 使用并发上传，使用并发上传时，除最后一块大小不定外，其余每个块大小固定为4M，
                .concurrentTaskCount(3) // 并发上传线程数量为3
                .responseTimeout(90) // 服务器响应超时。默认90秒
//                .recorder(recorder) // recorder分片上传时，已上传片记录器。默认null
//                .recorder(recorder, keyGen) // keyGen 分片上传时，生成标识符，用于片记录器区分是那个文件的上传记录
                .zone(FixedZone.zone0) // 设置区域，不指定会自动选择。指定不同区域的上传域名、备用域名、备用IP。
                .build()
            // 重用uploadManager。一般地，只需要创建一个uploadManager对象
            uploadManager = UploadManager(config)

            //内存泄漏
            if (LeakCanary.isInAnalyzerProcess(this)) {
                return
            }
            LeakCanary.install(this)


        }
    }

    private fun regToWx() {
        // 通过WXAPIFactory工厂，获取IWXAPI的实例
        api = WXAPIFactory.createWXAPI(this, APP_ID, true)

        // 将应用的appId注册到微信
        api.registerApp(APP_ID)

        //建议动态监听微信启动广播进行注册到微信
        registerReceiver(object : BroadcastReceiver() {
            override fun onReceive(context: Context?, intent: Intent?) {
                // 将该app注册到微信
                api.registerApp(APP_ID)
            }
        }, IntentFilter(ConstantsAPI.ACTION_REFRESH_WXAPP))
    }

    override fun netWorkState(status: Boolean) {
        netWorkState = status
    }

    override fun canShowDialog(): Boolean {
        return appForeground.value!!
    }

    /**
     * 获取当前进程的名字，一般就是当前app的包名
     *
     * @return 返回进程的名字
     */
    private fun getName(): String {
        val pid = android.os.Process.myPid()
        val activityManager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val list = activityManager.runningAppProcesses
        val i = list.iterator()
        while (i.hasNext()) {
            val info = (i.next()) as ActivityManager.RunningAppProcessInfo
            try {
                if (info.pid == pid) {
                    return info.processName
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
        return ""
    }

    /**
     *单点登录发生了
     */
    private fun onePointHappen(showToast: Boolean?) {
        //清除cid
        if (!TextUtils.isEmpty(KeyString.token)) {
            val cidRequest = CidRequest("")
            HttpHelper().updateCid(cidRequest)?.subscribe({}, {})
        }
        async {
            DataStoreUtils.writeStringToDataStore(DataStoreUtils.TOKEN, "")
//            startCalculate.value = false
            clearBlueToothData()
        }
        KeyString.token = ""
        communityChildId = -1
        refreshMainActivityUI = false
        ARouter.getInstance().build(LOGIN_ROUTER).withFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK).withBoolean(KeyString.showToast, showToast == true).navigation()
    }

    override fun onTerminate() {
        super.onTerminate()
        blueToothUtil?.stopScan()
        blueToothUtil?.disConnect()
        blueToothUtil?.finish()
    }

    fun homeless() {
        noFamilyActivityShow = true
        if (noFamilyActivityShow && mainHomePageSelect != 1) {
            noFamilyActivityShow = false
            val i = Intent(this, NoFamilyDialog::class.java)
            i.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            startActivity(i)
        }
    }

    fun openOtherFamily() {
        hasWeightMachine = false
        hasHeightMachine = false
        userData.deviceList?.forEach { d ->
            when (d.deviceType) {
                1 -> {
                    hasWeightMachine = true
                }
                2 -> {
                    hasHeightMachine = true
                }
                3 -> {
                    hasToothBrushMachine = true
                }
            }
        }
        val i = Intent(this, ChangeFamilyDialog::class.java)
        i.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        startActivity(i)
    }
}